/*
 * @Author: your name
 * @Date: 2021-12-23 14:53:01
 * @LastEditTime: 2021-12-24 16:53:45
 * @LastEditors: Please set LastEditors
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: \first_one_file\react-travel\src\redux\productDetail\slice.ts
 */
import { createSlice, PayloadAction, createAsyncThunk } from '@reduxjs/toolkit';
import axios from 'axios';

interface ProductSearchState {
  loading: boolean;
  error: string | null;
  data: any;
  pagination: any;
}

const initialState: ProductSearchState = { 
  loading: true,
  error: null,
  data: null,
  pagination: null
}

export const searchProduct = createAsyncThunk(
  "productSearch/searchProduct",
  async (paramaters: {
    keywords: string,
    nextPage: number | string,
    pageSize: number | string,
  }, thunkAPI) => {
    let url = `http://123.56.149.216:8080/api/touristRoutes?nextPage=${paramaters.nextPage}&pageSize=${paramaters.pageSize}`
    if (paramaters.keywords) {
      url += `&keywords=${paramaters.keywords}`
    }
    const response = await axios.get(url);
    return {
      data: response.data,
      pagination: JSON.parse(response.headers['x-pagination'])
    };
  }
);

export const productSearchSlice = createSlice({
  name: 'productSearch',
  initialState,
  reducers: {},
  extraReducers: {
    [searchProduct.pending.type]: (state) => {
      state.loading = true;
    },
    [searchProduct.fulfilled.type]: (state, action) => {
      state.data = action.payload.data;
      state.pagination = action.payload.pagination;
      state.loading = false;
      state.error = null;
    },
    [searchProduct.rejected.type]: (state, action: PayloadAction<string|null>) => {
      state.loading = false;
      state.error = action.payload;
    }
  }
})
